/*
 * @lc app=leetcode.cn id=7 lang=java
 *
 * [7] 整数反转
 */

// @lc code=start
class Solution {
    /**
     * Accepted
    1032/1032 cases passed (0 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 54.8 % of java submissions (38.8 MB)
     */
    public int reverse(int x) {
        if (x == 0)
            return 0;
        int result = 0;
        int maxVal = Integer.MAX_VALUE / 10;// MAX_VALUE=2^31−1=2,147,483,647
        int minVal = Integer.MIN_VALUE / 10;
        while (x != 0) {
            // 小于2^31的10位数，首位只能是1或2，反转过来末位是1或2，小于7。如果大于7，输入就溢出了。所以不用考虑末位的7和-8，只要保证其余9位满足条件就行。
            if (result > maxVal || result < minVal)
                return 0;
            result = result * 10 + (x % 10);
            x = x / 10;
        }
        return result;
    }
}
// @lc code=end
